package xiancheng.ticket;

/**
 * @author Mr.ma
 * @since 2022/11/1 20:28
 *
 * 使用自动锁解决线程安全问题
 **/
public class TestSync {
    public static void main(String[] args) {
        TestRunnable05 selling = new TestRunnable05();
        Thread thread1 = new Thread(selling, "窗口1");
        Thread thread2 = new Thread(selling, "窗口2");
        Thread thread3 = new Thread(selling, "窗口3");
        Thread thread4 = new Thread(selling, "窗口4");
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
    }
}

class TestRunnable05 implements Runnable{
    private Integer ticket=100;

    @Override
    public void run() {
        while (true){
            synchronized (ticket){
                if (ticket>0){
                    System.out.println(Thread.currentThread().getName()+"卖了一张票,剩余"+ --ticket);
                }else{
                    break;
                }
            }
        }
    }
}
